package com.ktjy.ktmall.service.impl;

import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ktjy.common.exception.ServiceException;
import com.ktjy.common.utils.StringUtils;
import com.ktjy.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktjy.ktmall.mapper.AttrMapper;
import com.ktjy.ktmall.domain.Attr;
import com.ktjy.ktmall.service.IAttrService;

import javax.validation.Validator;

/**
 * 规格属性Service业务层处理
 *
 * @author ktjy
 * @date 2025-03-13
 */
@Service
public class AttrServiceImpl extends ServiceImpl<AttrMapper, Attr>
        implements IAttrService {
    @Autowired
    private AttrMapper attrMapper;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询规格属性列表
     *
     * @param attr 规格属性
     * @return 规格属性
     */
    @Override
    public List<Attr> selectAttrList(Attr attr)
    {
        return attrMapper.selectAttrList(attr);
    }

    @Override
    public String importAttr(List<Attr> attrList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(attrList) || attrList.size() == 0) {
            throw new ServiceException("导入规格属性数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Attr attr : attrList) {
            try {
                // 验证数据的合法性等操作
                // 例如：检查规格属性名称是否唯一等
                // 如果数据合法，插入或更新数据库
                attrMapper.insertAttr(attr);
                successNum++;
                successMsg.append("<br/>" + successNum + "、规格属性 " + attr.getName() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、规格属性 " + attr.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<Attr> getAttrListByAttrId(Long attrId, String stockSku) {
        return attrMapper.getAttrListByAttrId(attrId, stockSku);
    }
}